<template>
  <div class="repair-personnel-management">
    <t-card title="维修人员管理">
      <div class="search-bar">
        <t-input v-model="searchUsername" placeholder="搜索用户名" class="search-input" />
        <t-input v-model="searchGender" placeholder="性别" class="search-input"/>
        <el-button @click="searchPersonnel" class="search-button" type="primary" icon="search">搜索</el-button>
        <el-button @click="openAddPersonnelDialog" class="add-button" type="primary" icon="add">添加维修人员</el-button>
      </div>
      <div class="table-container">
        <t-table :data="personnel" :columns="columns" :loading="loading" row-key="repairPersonnelId" class="personnel-table">
          <template #username="{ row }">
            <span>{{ row.username }}</span>
          </template>
          <template #fullName="{ row }">
            <span>{{ row.fullName }}</span>
          </template>
          <template #gender="{ row }">
            <span>{{ row.gender }}</span>
          </template>
          <template #maintenanceType="{ row }">
            <span>{{ row.maintenanceType }}</span>
          </template>
          <template #email="{ row }">
            <span>{{ row.email }}</span>
          </template>
          <template #phone="{ row }">
            <span>{{ row.phone }}</span>
          </template>
          <template #price="{ row }">
            <span>{{ row.price }}</span>
          </template>
          <template #actions="{ row }">
            <el-button theme="primary" @click="openEditPersonnelDialog(row)" class="action-button">修改</el-button>
            <el-button theme="danger" @click="deletePersonnel(row.repairPersonnelId)" class="action-button">删除</el-button>
          </template>
        </t-table>
      </div>
      <div class="pagination-container">
        <t-pagination
            v-model:current="page"
            v-model:pageSize="pageSize"
            :total="total"
            @change="fetchPersonnel"
            class="pagination"
        />
      </div>
    </t-card>

    <!-- 添加/修改维修人员对话框 -->
    <t-dialog :visible.sync="personnelDialogVisible" :title="dialogTitle" width="500px">
      <t-form :model="personnelForm" :rules="rules" ref="personnelFormRef" @submit.prevent="handlePersonnelDialogConfirm">
        <t-form-item label="用户名" name="username">
          <t-input v-model="personnelForm.username" />
        </t-form-item>
        <t-form-item label="姓名" name="fullName">
          <t-input v-model="personnelForm.fullName" />
        </t-form-item>
        <t-form-item label="性别" name="gender">
          <t-select v-model="personnelForm.gender">
            <t-option value="男">男</t-option>
            <t-option value="女">女</t-option>
            <t-option value="其他">其他</t-option>
          </t-select>
        </t-form-item>
        <t-form-item label="维护类型" name="maintenanceType">
          <t-input v-model="personnelForm.maintenanceType" />
        </t-form-item>
        <t-form-item label="邮箱" name="email">
          <t-input v-model="personnelForm.email" />
        </t-form-item>
        <t-form-item label="电话" name="phone">
          <t-input v-model="personnelForm.phone" />
        </t-form-item>
        <t-form-item label="价格" name="price">
          <t-input v-model="personnelForm.price" />
        </t-form-item>
        <t-form-item label="密码" name="password">
          <t-input type="password" v-model="personnelForm.password" />
        </t-form-item>
        <t-form-item label="创建时间" name="createTime">
          <t-date-picker v-model="personnelForm.createTime" format="YYYY-MM-DD HH:mm:ss" />
        </t-form-item>
        <t-form-item label="更新时间" name="updateTime">
          <t-date-picker v-model="personnelForm.updateTime" format="YYYY-MM-DD HH:mm:ss" />
        </t-form-item>
        <div class="dialog-footer">
          <el-button @click="handleDialogCancel" type="default">取消</el-button>
          <el-button @click="handlePersonnelDialogConfirm" type="primary">确认</el-button>
        </div>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const searchUsername = ref('');
const searchGender = ref('');
const personnel = ref([]);
const loading = ref(false);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

const personnelDialogVisible = ref(false);
const dialogTitle = ref('');
const personnelFormRef = ref(null);
const personnelForm = reactive({
  username: '',
  fullName: '',
  gender: '',
  maintenanceType: '',
  email: '',
  phone: '',
  price: '',
  password: '',
  createTime: '',
  updateTime: '',
});
const originalPersonnelForm = reactive({ ...personnelForm }); // 保存原始的维修人员表单数据
const rules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  fullName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  email: [{ required: true, type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
  phone: [{ required: true, message: '电话不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
};

const columns = [
  { title: '用户名', colKey: 'username', slot: 'username' },
  { title: '姓名', colKey: 'fullName', slot: 'fullName' },
  { title: '性别', colKey: 'gender', slot: 'gender' },
  { title: '维护类型', colKey: 'maintenanceType', slot: 'maintenanceType' },
  { title: '邮箱', colKey: 'email', slot: 'email' },
  { title: '电话', colKey: 'phone', slot: 'phone' },
  { title: '价格', colKey: 'price', slot: 'price' },
  { title: '操作', colKey: 'actions', slot: 'actions' },
];

const fetchPersonnel = async () => {
  loading.value = true;
  try {
    const response = await getRepairPersonnel({ pageNum: page.value, pageSize: pageSize.value, param: { username: searchUsername.value, gender: searchGender.value } });
    personnel.value = response.data.data;
    total.value = response.data.total;
  } catch (error) {
    console.error('获取维修人员数据失败:', error);
    ElMessage.error('获取维修人员数据失败');
  } finally {
    loading.value = false;
  }
};

const searchPersonnel = () => {
  page.value = 1;
  fetchPersonnel();
};

const deletePersonnel = async (repairPersonnelId) => {
  const confirm = window.confirm('确定删除该维修人员吗？');
  if (confirm) {
    try {
      await deleteRepairPersonnelById(repairPersonnelId);
      fetchPersonnel();
      ElMessage.success('维修人员删除成功');
    } catch (error) {
      console.error('删除维修人员失败:', error);
      ElMessage.error('删除维修人员失败');
    }
  }
};

const handlePersonnelDialogConfirm = async () => {
  personnelFormRef.value.validate().then(async () => {
    try {
      const isModified = Object.keys(personnelForm).some(key => personnelForm[key] !== originalPersonnelForm[key]);
      if (!isModified) {
        ElMessage.info('没有修改任何信息');
        return;
      }
      const currentTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
      if (!personnelForm.createTime) {
        personnelForm.createTime = currentTime;
      }
      personnelForm.updateTime = currentTime;
      await saveRepairPersonnel(personnelForm);
      closeDialog();
      fetchPersonnel();
      ElMessage.success(dialogTitle.value === '添加维修人员' ? '维修人员添加成功' : '维修人员修改成功');
    } catch (error) {
      console.error('操作失败:', error);
      ElMessage.error('操作失败');
    }
  }).catch(() => {
    console.log('表单验证失败');
    ElMessage.warning('表单验证失败');
  });
};

const openAddPersonnelDialog = () => {
  Object.keys(personnelForm).forEach(key => {
    personnelForm[key] = '';
  });
  Object.assign(originalPersonnelForm, { ...personnelForm }); // 重置原始维修人员表单数据
  dialogTitle.value = '添加维修人员';
  personnelDialogVisible.value = true;
};

const openEditPersonnelDialog = (personnel) => {
  Object.assign(personnelForm, personnel);
  Object.assign(originalPersonnelForm, { ...personnelForm }); // 记录原始维修人员表单数据
  dialogTitle.value = '修改维修人员';
  personnelDialogVisible.value = true;
};

const handleDialogCancel = () => {
  console.log('handleDialogCancel 被调用');
  // 手动重置表单字段
  Object.keys(personnelForm).forEach(key => {
    personnelForm[key] = ''; // 重置为原始值
  });
  // personnelFormRef.value.resetFields(); // 重置表单验证状态
  closeDialog(); // 关闭对话框
};

const closeDialog = () => {
  console.log('closeDialog 被调用');
  personnelDialogVisible.value = false;
};

// API 调用函数
const getRepairPersonnel = (params) => {
  return axios.post('http://localhost:8080/repair/listRepairPersonnelPage1', params, {
    headers: {
      'Content-Type': 'application/json'
    }
  });
};

const deleteRepairPersonnelById = (repairPersonnelId) => {
  return axios.get(`http://localhost:8080/repair/delete?repair_personnel_id=${repairPersonnelId}`);
};

const saveRepairPersonnel = (personnel) => {
  return axios.post('http://localhost:8080/repair/saveOrMod', personnel);
};

onMounted(fetchPersonnel);

// 监听分页变化
watch([page, pageSize], fetchPersonnel);
</script>

<style scoped>
.repair-personnel-management {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}

.search-input {
  flex: 1;
}

.search-button, .add-button {
  transition: transform 0.2s;
}

.search-button:hover, .add-button:hover {
  transform: scale(1.05);
}

.t-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.table-container {
  flex: 1;
  overflow: auto;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.action-button {
  margin-right: 8px;
  transition: background-color 0.2s;
}

.action-button:hover {
  background-color: #23443c;
  color: #ffffff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer .t-button {
  margin-left: 8px;
}
</style>
